<script setup lang="ts">

import {IconPlus} from "@arco-design/web-vue/es/icon";
import type {optionsType} from "@/api";
import {
  aiRoleAvatarOptions,
  aiRoleCategoryOptions, aiRoleUpdateAdminApi, aiRoleUpdateUserApi,
  type aiRoleUpdateAdminType,
  type aiRoleUpdateUserType
} from "@/api/ai_role_api";
import {userStorei} from "@/stores/user_store";
import type { FileItem} from "@arco-design/web-vue";
import {type baseResponse, getOptions} from "@/api";
import {Message} from "@arco-design/web-vue";
import {ref, reactive, watch} from "vue";
import type { aiRoleCreateType} from "@/api/ai_role_api";
import {aiRoleCreateApi} from "@/api/ai_role_api";
interface aiRoleUpdateDetailType {
  admin: aiRoleUpdateAdminType
  user: aiRoleUpdateUserType
}

interface Props {
  visible: boolean
  type: keyof aiRoleUpdateDetailType
  detail?: aiRoleUpdateAdminType | aiRoleUpdateUserType
}
const props = defineProps<Props>()
const emits = defineEmits(["update:visible", "ok"])

const store = userStorei()



const data = reactive<aiRoleCreateType|aiRoleUpdateUserType>({
  title: "",
  avatar: "",
  category: "",
  abstract: "",
  prompt: "",
  reason: ""
})

const formRef = ref()

async function aiRoleHandler() {
  const val = await formRef.value.validate()
  if (val) {
    return false
  }
  let res: baseResponse<string>
  // 判断是更新还是创建
  if (props.detail === undefined || props.detail?.roleID == 0) {
    res = await aiRoleCreateApi(data)
  } else {
    // 更新
    if (props.type == "admin") {
      res = await aiRoleUpdateAdminApi({...data, roleID: (props.detail as aiRoleUpdateAdminType).roleID})
    } else {
      res = await aiRoleUpdateUserApi({...data,
        reason: (data as aiRoleUpdateUserType).reason,
        roleID: (props.detail as aiRoleUpdateUserType).roleID})
    }
  }
  if (res.code) {
    Message.error(res.msg)
    return false
  }
  Message.success(res.msg)
  emits("ok")
  emits("update:visible", false)
  return
}

const avatarOptions = ref<optionsType[]>([])
getOptions(aiRoleAvatarOptions, avatarOptions)
const categoryOptions = ref<optionsType[]>([])
getOptions(aiRoleCategoryOptions, categoryOptions)


function fileSuccess(fileItem: FileItem) {
  const res = fileItem.response as baseResponse<string>
  if (res.code) {
    Message.error(res.msg)
    return
  }
  Message.success("上传成功")
  data.avatar = res.data
  // 查一下，是不是已经有相同的图片了
  const item = avatarOptions.value.find((item) => {
    return item.value === res.data
  })
  if (item) {
    // 已经有相同的了
    return;
  }

  avatarOptions.value.push({
    label: res.data,
    value: res.data
  })

}
watch(() => props.detail, () => {
  Object.assign(data, props.detail)
}, {deep: true})
function close() {
  emits("update:visible", false)
}

</script>

<template>
  <div class="f_ai_role_create">
    <a-modal :title="props.detail ? ((props.detail as aiRoleUpdateAdminType).roleID ? '更新角色' : '创建角色') : '创建角色'" :visible="props.visible"
             :on-before-ok="aiRoleHandler" @cancel="close">
      <a-form ref="formRef" :model="data">
        <a-form-item v-if="props.detail ? ((props.detail as aiRoleUpdateUserType).isSquare && props.type === 'user'): false" label="更新理由"
                     field="reason" :rules="[{required: true}]" validate-trigger="blur">
          <a-textarea v-model="(data as aiRoleUpdateUserType).reason" :auto-size="{minRows: 4, maxRows: 5}" placeholder="更新理由"></a-textarea>
        </a-form-item>
        <a-form-item label="角色名称" field="title" :rules="[{required: true}]" validate-trigger="blur">
          <a-input placeholder="角色名称" v-model="data.title"></a-input>
        </a-form-item>
        <a-form-item label="角色图标">
          <div class="ai_role_avatar">
            <div class="ai_role_avatar_list">
              <a-radio-group v-model="data.avatar">
                <a-radio :value="item.value" v-for="item in avatarOptions">
                  <a-avatar :image-url="item.label" :size="40" shape="square"></a-avatar>
                </a-radio>
              </a-radio-group>
            </div>
            <a-upload
                :show-file-list="false"
                action="/api/image"
                name="file"
                :headers="{token: store.userInfo.token}"
                @success="fileSuccess">
              <template #upload-button>
                <div class="upload_btn">
                  <IconPlus></IconPlus>
                </div>
              </template>
            </a-upload>
          </div>


        </a-form-item>
        <a-form-item label="角色分类">
          <a-select allow-create placeholder="角色分类" :options="categoryOptions" v-model="data.category"></a-select>
        </a-form-item>
        <a-form-item label="角色介绍" field="abstract" :rules="[{required: true}]" validate-trigger="blur">
          <a-textarea v-model="data.abstract" :auto-size="{minRows: 4, maxRows: 5}" placeholder="角色介绍"></a-textarea>
        </a-form-item>
        <a-form-item label="prompt" field="prompt" :rules="[{required: true}]" validate-trigger="blur">
          <a-textarea v-model="data.prompt" :auto-size="{minRows: 4, maxRows: 5}" placeholder="角色提示词"></a-textarea>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<style lang="less">
.ai_role_avatar {
  width: 100%;

  .ai_role_avatar_list {
    border: 1px solid var(--color-neutral-3);
    border-radius: 5px;
    padding: 10px;
    max-height: 200px;
    overflow-y: auto;

    .arco-radio-group {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      grid-row-gap: 10px;
    }
  }

  .arco-upload {
    width: 100%;
  }

  .upload_btn {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 5px;
    width: 100%;
    height: 40px;
    border-radius: 5px;
    border: 1px solid var(--color-neutral-3);
    margin-right: 10px;

    svg {
      color: var(--color-text-2);
    }
  }
}</style>